package com.sjy.project.fym.user.controller;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sjy.framework.aspectj.lang.annotation.Log;
import com.sjy.framework.aspectj.lang.enums.BusinessType;
import com.sjy.project.fym.place.domain.FyPlace;
import com.sjy.project.fym.place.service.IFyPlaceService;
import com.sjy.project.fym.team.domain.FyTeam;
import com.sjy.project.fym.team.service.IFyTeamService;
import com.sjy.project.fym.user.domain.FyUser;
import com.sjy.project.fym.user.service.IFyUserService;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import com.sjy.framework.web.controller.BaseController;
import com.sjy.framework.web.domain.AjaxResult;
import com.sjy.framework.web.domain.Ztree;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.poi.ExcelUtil;
import com.sjy.framework.web.page.TableDataInfo;

/**
 * 防疫人员信息Controller
 * 
 * @author sjy
 * @date 2022-04-18
 */
@Controller
@RequestMapping("/fym/user")
public class FyUserController extends BaseController
{
    private String prefix = "fym/user";

    @Autowired
    private IFyUserService fyUserService;
    @Autowired
    private IFyPlaceService fyPlaceService;
    @Autowired
    private IFyTeamService fyTeamService;

    @RequiresPermissions("fym:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }

    /**
     * 查询防疫人员信息列表
     */
    @RequiresPermissions("fym:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FyUser fyUser)
    {
        startPage();
        List<FyUser> list = fyUserService.selectFyUserList(fyUser);
        return getDataTable(list);
    }

    /**
     * 导出防疫人员信息列表
     */
    @RequiresPermissions("fym:user:export")
    @Log(title = "防疫人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FyUser fyUser)
    {
        List<FyUser> list = fyUserService.selectFyUserList(fyUser);
        ExcelUtil<FyUser> util = new ExcelUtil<FyUser>(FyUser.class);
        return util.exportExcel(list, "防疫人员信息数据");
    }
    /**
     * 导入数据
     */
    @RequiresPermissions("fym:user:import")
    @Log(title = "防疫人员信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FyUser> util = new ExcelUtil<FyUser>(FyUser.class);
        List<FyUser> list = util.importExcel(file.getInputStream());
        String message = fyUserService.importUser(list, updateSupport);
        return AjaxResult.success(message);
    }
    @RequiresPermissions("fym:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<FyUser> util = new ExcelUtil<FyUser>(FyUser.class);
        return util.importTemplateExcel("防疫人员数据");
    }

    /**
     * 新增防疫人员信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
    	List<FyTeam> fyTeams = fyTeamService.selectFyTeamList(null);
    	mmap.put("fyTeams", fyTeams);
        return prefix + "/add";
    }

    /**
     * 新增保存防疫人员信息
     */
    @RequiresPermissions("fym:user:add")
    @Log(title = "防疫人员信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FyUser fyUser)
    {
        return toAjax(fyUserService.insertFyUser(fyUser));
    }

    /**
     * 修改防疫人员信息
     */
    @RequiresPermissions("fym:user:edit")
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        FyUser fyUser = fyUserService.selectFyUserByUserId(userId);
        mmap.put("fyUser", fyUser);

    	List<FyTeam> fyTeams = fyTeamService.selectFyTeamList(null);
    	mmap.put("fyTeams", fyTeams);
        return prefix + "/edit";
    }
    
    /**
     * 修改防疫人员、队伍、场所
     * @param userId
     * @param mmap
     * @return
     */
    @GetMapping("/editPlaceTeam")
    public String editPlaceTeam( ModelMap mmap)
    {
//        List<FyPlace> fyPlaces = fyPlaceService.selectFyPlaceList(null);
//        List<FyTeam> fyTeams = fyTeamService.selectFyTeamList(null);
//        mmap.put("fyPlaces", fyPlaces);
//        mmap.put("fyTeams", fyTeams);
        return prefix + "/placeTeamUser";
    }

    /**
     * 批量保存防疫队伍跟防疫人员分配关系
     */
    @RequiresPermissions("fym:user:edit")
    @Log(title = "防疫人员队伍分配", businessType = BusinessType.UPDATE)
    @PostMapping("/batchEdit")
    @ResponseBody
    public AjaxResult batchEdit(Long teamId,String userIds)
    {
        return toAjax(fyUserService.updateFyUserIds(teamId,userIds));
    }
    
    /**
     * 修改保存防疫人员信息
     */
    @RequiresPermissions("fym:user:edit")
    @Log(title = "防疫人员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FyUser fyUser)
    {
        return toAjax(fyUserService.updateFyUser(fyUser));
    }
    
    /**
     * 打开批量发送短信息页面
     */
    @RequiresPermissions("fym:user:edit")
    @GetMapping("/sendMsgMultiple/{userIds}")
    public String sendMsgMultiple(@PathVariable("userIds") String userIds, ModelMap mmap)
    {
    	System.out.println(userIds);
        //批量获取人员的名称
        String userNames = fyUserService.selectFyUserNamesByUserIds(userIds);
    	mmap.put("userIds", userIds);
        mmap.put("userNames", userNames);
        mmap.put("msgContent", "温馨提示：您被分配xx防疫队伍，请xxx防疫人员尽快到达指定核酸采样点xxx，采样点具体位置为：xxxx，入场防疫检测需要一定时间，请尽快前往指定核酸点，并进行核酸点扫码签到打卡！【“e企管平台”（疫情防控）】\r\n" + 
        		"联系人：张程虹，咨询电话：0577-86801007，手机号码：15057572589。");
        return prefix + "/send_msg_mulitiple";
    }
    /**
     * 批量发送短信息
     */
    @RequiresPermissions("fym:user:edit")
    @Log(title = "防疫人员短信息批量发送", businessType = BusinessType.INSERT)
    @PostMapping("/sendMsgMultiple")
    @ResponseBody
    public AjaxResult sendMsgMultiple(String userIds)
    {
    	System.out.println(userIds);
    	//调用短信接口
    	if(StringUtils.isBlank(userIds)) {
    		return toAjax(0);
    	}
    	//获取人员、防疫点、队伍信息、并发送短信
    	String[] userIdArr = userIds.split(",");
    	int successNum = 0;
    	String result = "";
    	for(String userId:userIdArr) {
    		FyUser user = fyUserService.selectFyUserByUserId(Long.parseLong(userId));
    		if(user!=null&&!"2".equals(user.getDelFlag())) {
    			FyTeam team = user.getFyTeam();
    			FyPlace place = fyPlaceService.selectById(team.getPlaceId());
    			String msgContent = "{\"team\":\""+team.getTeamName()+"\",\"mobile\":\""+user.getPhonenumber()+"\",\"type\":4,\"name\":\""+user.getUserName()+"\",\"cyd\":\""+place.getPlaceName()+"\",\"address\":\""+place.getAddr()+"\"}";
    			System.out.println(msgContent);
    			HttpResponse response = HttpUtil.createPost("http://10.36.196.18:8081/phone/msg/send")
    					.header("Content-Type", "application/json").charset("utf-8").body("{\"team\":\""+team.getTeamName()+"\",\"mobiles\":[\""+user.getPhonenumber()+"\"],\"type\":4,\"name\":\""+user.getUserName()+"\",\"cyd\":\""+place.getPlaceName()+"\",\"address\":\""+place.getAddr()+"\"}")
    					.execute();
    			result = response.body();
    		}
    	}
    	
		//return response;
    	return AjaxResult.success(result);
        //return toAjax(fyPlaceService.updateFyPlaceMultiple(placeIds,status,signInRadius));
    }
    /**
     * 删除防疫人员信息
     */
    @RequiresPermissions("fym:user:remove")
    @Log(title = "防疫人员信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(fyUserService.deleteFyUserByUserIds(ids));
    }
    
    /**
     * 加载人员列表树
     */
    @PostMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData(Long teamId,boolean checked)
    {
    	System.out.println(teamId);
    	System.out.println(checked);
        List<Ztree> ztrees = fyUserService.selectUserTree(new FyUser(),teamId,checked);
        return ztrees;
    }
}
